<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约系统 - 医生</title>
    <script src="{{url_for('static', filename='js/jquery-3.6.0.min.js')}}"></script>
    <script src="{{url_for('static', filename='js/custom_message_box.js')}}"></script>
    <link rel="stylesheet" href="{{url_for('static', filename='css/custom_message_box.css')}}">
    <link href="{{url_for('static', filename='css/layui.css')}}" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
            padding: 10px;
            background: url("{{url_for('static', filename='img/login_admin_web.jpg')}}") no-repeat center;
            height: 800px;
            background-size: cover;
        }

        h1,
        h2 {
            border-bottom: 2px solid #ccc;
            padding-bottom: 5px;
        }

        #profile-info,
        #appointments-list {
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .appointment-item {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
        }

        .logout-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin-top: 10px;
            cursor: pointer;
        }

        .logout-btn:hover {
            background-color: #d32f2f;
        }

        .operation-btn {
            background-color: #FF9800;
            color: white;
            border: none;
            padding: 5px 10px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            cursor: pointer;
        }

        .operation-btn.disabled {
            background-color: #ccc;
            /* 禁用时的背景色 */
            cursor: not-allowed;
            /* 鼠标样式为不可点击 */
        }

        .operation-btn:hover:not(.disabled) {
            background-color: #F57C00;
        }

        #pending-appointments-list {
            background-color: skyblue;
        }

        #doctor-appointments-list {
            background-color: skyblue;
        }
    </style>
    <script>
        function translateToChinese(stringa) {
            switch (stringa) {
                case 'pending':
                    return '待处理';
                case 'accepted':
                    return '已接受';
                case 'rejected':
                    return '已拒绝';
                case 'completed':
                    return '已完成';
                case 'cancelled':
                    return '已取消';
                default:
                    return stringa;
            }
        }
        function queryPackages() {
            $.ajax({
                url: "{{ url_for('doctor.query_package') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({}),
                success: function ({ code, data, message }) {
                    if (code !== 0) {
                        showMessage("error", message || "获取套餐列表失败，请稍后再试。", "message", 3000);
                        return;
                    }

                    let packageSelect = $('#package-select');
                    packageSelect.empty();
                    data.forEach(({ id, name, description }) => {
                        packageSelect.append($('<option>', {
                            value: id,
                            text: `${name} - ${description}`
                        }));
                    });
                    loadPackageDetails(data[0].id)
                },
                error: function () {
                    showMessage("error", "网络错误，获取套餐列表失败，请稍后再试。", "message", 3000);
                }
            });
        }

        function loadPackageDetails(packageId) {
            if (!packageId) return;
            $.ajax({
                url: "{{ url_for('doctor.query_package_items') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ package_id: packageId }),
                success: function (response) {
                    if (response.code === 0) {
                        let itemsContainer = $('#package-items');
                        itemsContainer.empty();
                        response.data.forEach(function (item) {
                            // 注意：根据返回的数据结构调整内容展示
                            itemsContainer.append(`<p>项目ID: ${item.id}, 内容: ${item.content}</p>`);
                        });
                    } else {
                        showMessage("error", response.message, "message", 3000);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    showMessage("error", "获取项目列表失败：" + textStatus + " " + errorThrown, "message", 3000);
                }
            });
        }
        // 异步函数，返回 Promise 对象以处理异步调用
        function getPackageInfoByID(package_id) {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: "{{ url_for('doctor.query_package') }}",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify({ id: package_id }),
                    success: function (response) {
                        if (response.code === 0) {
                            resolve(response.data[0]); // 成功时返回数据
                        } else {
                            reject(response.message); // 失败时返回错误信息
                        }
                    },
                    error: function (xhr, status, error) {
                        reject('Error fetching package info: ' + error); // AJAX 请求失败时返回错误
                    }
                });
            });
        }
        async function getPendingAppointmentsData() {
            try {
                const response = await $.ajax({
                    url: "{{ url_for('doctor.get_pending_appointments') }}",
                    type: 'GET'
                });

                if (response.code === 0) {
                    return response.data;
                } else {
                    throw new Error(response.message);
                }
            } catch (error) {
                throw new Error('Error fetching appointments: ' + error);
            }
        }
        async function getDoctorAppointmentsData() {
            try {
                const response = await $.ajax({
                    url: "{{ url_for('doctor.get_doctor_appointments') }}",
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({}),
                });
                console.log(response)
                if (response.code === 0) {
                    return response.data;
                } else {
                    throw new Error(response.message);
                }
            } catch (error) {
                throw new Error('Error fetching doctor appointments: ' + error);
            }
        }
        function acceptAppointment(appointmentID) {
            $.ajax({
                url: "{{ url_for('doctor.accept_appointment') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ appointment_id: appointmentID }),
                success: function (response) {
                    if (response.code == 0) {
                        showMessage('success', "Successfully accepted appointment", 'message', 3000);
                        refreshPatientAppointments()
                        return
                    }
                    showMessage('error', "fail to accept appointment", 'message', 3000);

                }
            })

        }
        function rejectAppointment(appointmentID) {
            $.ajax({
                url: "{{ url_for('doctor.reject_appointment') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ appointment_id: appointmentID }),
                success: function (response) {
                    if (response.code == 0) {
                        showMessage('success', "Successfully rejected appointment", 'message', 3000);
                        refreshPatientAppointments()
                        return
                    }
                    showMessage('error', "fail to reject appointment", 'message', 3000);

                }
            })

        }
        function updateResult(appointmentID, result) {
            $.ajax({
                url: "{{ url_for('doctor.update_result') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ appointment_id: appointmentID, result: $('#resultInput').val() }),
                success: function (response) {
                    if (response.code == 0) {
                        showMessage('success', "Successfully updated appointment result", 'message', 3000);
                        refreshPatientAppointments()
                        return
                    }
                    showMessage('error', "fail to update appointment result", 'message', 3000);

                }
            })
        }
        function completeAppointment(appointmentID) {
            $.ajax({
                url: "{{ url_for('doctor.complete_appointment') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ appointment_id: appointmentID }),
                success: function (response) {
                    if (response.code == 0) {
                        showMessage('success', "Successfully finished appointment", 'message', 3000);
                        refreshPatientAppointments()
                        return
                    }
                    showMessage('error', "fail to finish appointment", 'message', 3000);

                }
            })
        }
        async function renderAppointments(appointments, selector) {
            var html = '<table>';
            html += '<tr><th>预约编号</th><th>预约套餐名称</th><th>预约套餐描述</th><th>预约时间</th><th>预约状态</th><th>预约结果</th><th>操作</th></tr>';

            for (var i = 0; i < appointments.length; i++) {
                try {
                    // 等待每个 package 信息的获取完成
                    const pkginfo = await getPackageInfoByID(appointments[i].package_id);

                    // 构建表格行
                    html += '<tr>';
                    html += '<td>' + appointments[i].id + '</td>';
                    html += '<td>' + pkginfo.name + '</td>';
                    html += '<td>' + pkginfo.description + '</td>';
                    html += '<td>' + appointments[i].appointment_time + '</td>';
                    html += '<td>' + translateToChinese(appointments[i].status) + '</td>';
                    html += '<td>'
                    if (appointments[i].status != "accepted") {
                        html += translateToChinese(appointments[i].result);
                    }
                    else {
                        if (appointments[i].result != null) {
                            html += '<input value="' + appointments[i].result + '" placeholder="填写预约结果" id="resultInput"></input>'
                        }
                        else {
                            html += '<input value="" placeholder="填写预约结果" id="resultInput"></input>'
                        }
                    }
                    html += '</td>'
                    // 根据预约状态确定按钮状态和文本
                    switch (appointments[i].status) {
                        case 'pending':
                            html += '<td><button class="operation-btn" onclick="acceptAppointment(' + appointments[i].id + ')">接受预约</button>&nbsp;<button class="operation-btn" onclick="rejectAppointment(' + appointments[i].id + ')">拒绝预约</button></td>';
                            break;
                        case 'cancelled':
                            html += '<td><button class="operation-btn disabled">已取消</button></td>';
                            break;
                        case 'rejected':
                            html += '<td><button class="operation-btn disabled">已拒绝</button></td>';
                            break;
                        case 'accepted':
                            html += '<td><button class="operation-btn" onclick="updateResult(' + appointments[i].id + ')">提交预约结果</button>&nbsp;<button class="operation-btn" onclick="completeAppointment(' + appointments[i].id + ')">完成预约</button></td>';
                            break;
                        case 'completed':
                            html += '<td><button class="operation-btn disabled">已完成</button></td>';
                            break;
                        default:
                            html += '<td><button class="operation-btn disabled">未知状态</button></td>';
                            break;
                    }

                    html += '</tr>';
                } catch (error) {
                    console.error('Error fetching package info:', error);
                    // 处理 package 信息获取失败的情况
                }
            }

            html += '</table>';

            // 更新 HTML 到指定的元素
            $(selector).html(html);
        }

        async function refreshPatientAppointments() {
            try {
                const DoctorAppointments = await getDoctorAppointmentsData();
                await renderAppointments(DoctorAppointments, "#doctor-appointments-list");
                const PendingAppointments = await getPendingAppointmentsData();
                await renderAppointments(PendingAppointments, "#pending-appointments-list");
            } catch (error) {
                alert(error);
            }
        }

        $(document).ready(function () {
            // 假设session中的doctor_id已经通过某种方式存储，这里用localStorage模拟
            var doctor_id = localStorage.getItem('doctor_id');

            // 调用函数以获取数据
            refreshPatientAppointments();

            // 添加退出登录功能
            $('#logoutBtn').click(function () {
                // 清除本地存储或者其他操作以注销用户
                localStorage.removeItem('doctor_id');
                // 可以重定向到登录页面或其他逻辑
                window.location.replace("{{ url_for('doctor.login_doctor_web') }}");
            });

        });
    </script>
</head>

<body>
    <div id="message" class="message-box"></div>

    <h2>预约信息</h2>
    <h3>负责的体检</h3>
    <div id="doctor-appointments-list"></div>
    <h3>可接受的体检</h3>
    <div id="pending-appointments-list"></div>


    <div style="">
        <button style="text-align: center" class="layui-btn layui-btn-normal layui-btn-radius">
            <a href="{{ url_for('doctor.dashboard_doctor_web') }}">返回面板主页</a>
        </button>
    </div>

    <!-- 其他页面内容 -->
</body>

</html>